import 'dart:async';
import 'dart:convert';
import 'package:flt_telephony_info/flt_telephony_info.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qgchat/common/action/index.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/apis/api.dart';
import 'package:qgchat/widgets/tipsDialog.dart';
import 'package:openinstall_flutter_plugin/openinstall_flutter_plugin.dart';
import 'package:shared_preferences/shared_preferences.dart';

/*
 * 登录
 * page登录
 */

class Login extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  OpeninstallFlutterPlugin _openinstallFlutterPlugin =
      OpeninstallFlutterPlugin();
  String _phoneId;
  String invationToken;

  // Qq _tencent = Qq();

  Future wakeupHandler(Map<String, dynamic> data) async {
    if (data['bindData'] != null) {
      Map map = json.decode(data['bindData']);
      if (map.containsKey('invation_token')) {
        invationToken = map['invation_token'];
      }
    }
  }

  Future installHandler(Map<String, dynamic> data) async {
    // TipsDialog.test(context, ["$data"]);
    if (data['bindData'] != null && data['bindData'].isNotEmpty) {
      Map map = json.decode(data['bindData']);
      if (map.containsKey('invation_token')) {
        invationToken = map['invation_token'];
      }
    }
  }

  @override
  void initState() {
    super.initState();
    _openinstallFlutterPlugin.init(wakeupHandler); // 拉起
    _openinstallFlutterPlugin.install(installHandler); // 安装

    // 获取设备信息
    _getPhoneInfo();

    // 统计下载效果点
    _downTotal();
    
    apkChannel();
  }

  @override
  void dispose() {
    super.dispose();
    // _tencent?.dispose();
  }

  // 渠道功能
  apkChannel() {
    switch (Config.apkChannel) {
      case ApkChannel.baidu:
        baiduAd();
        break;
      default:
    }
  }

  // 百度激活
  baiduAd() {
    PermissionHandler()
        .requestPermissions([PermissionGroup.phone]).then((res) async {
      final prefs = await SharedPreferences.getInstance(); // 初始化缓存
      final baidFirst = prefs.getString("baid_first");
      final baidSecond = prefs.getString("baid_second");
      final now = DateTime.now().millisecondsSinceEpoch;
      TelephonyInfo info = await FltTelephonyInfo.info;
      final anid = info.meid;

      if (empty(baidFirst)) {
        CommonApis.baiduActive(anid);
        prefs.setString("baid_first", "$now");
      } else {
        int setTime = int.parse(baidFirst);
        int waitTime = 60 * 60 * 24 * 1000;
        if (setTime + waitTime < now && empty(baidSecond)) {
          CommonApis.baiduNextDay(anid);
          prefs.setString("baid_second", "$now");
        }
      }
    });
  }

  // 统计下载
  _downTotal() {
    bool firstDown = cache.getBool("firstDown");
    if (firstDown != null && firstDown) return;
    cache.setBool("firstDown", true);
    _openinstallFlutterPlugin.reportEffectPoint("download_count", 1);
  }

  // 手机登录
  void _phoneLogin() {
    goPage(context, '/phoneLogin');
  }

  // 微信和qq登录
  void _login(name, openid, url) {
    // 登录
    UserApis.wxLogin(
      name,
      openid,
      url,
      _phoneId,
      invationToken,
    ).then((res) async {
      if (res != null && res['status'] == 1) {
        if (res['data']['register'] == 1) {
          _openinstallFlutterPlugin.reportRegister(); // 注册统计
        }
        await CommonAction.initAppData(context, res['data']['token']);
        showToast("登录成功");
        goPage(context, "/", replace: true);
      }
    });
  }

  // 获取设备信息
  void _getPhoneInfo() async {
    _phoneId = await CommonAction.deviceInfo();
  }

// widget-----------------------------------------------------------------------

  /// 背景图
  Widget BG() {
    return Container(
      width: w100(context),
      height: h100(context),
      child: Image.asset(
        'assets/images/homeBg.png',
        fit: BoxFit.cover,
      ),
    );
  }

  /// logo
  Widget logo() {
    return Container(
      width: w100(context),
      margin: EdgeInsets.only(top: px(250)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          /// logo
          Container(
            width: px(154),
            height: px(154),
            child: Image.asset('assets/images/icon/logo.jpg'),
          ),

          /// logoText
          Container(
            width: px(318),
            margin: EdgeInsets.only(top: px(34)),
            child: Image.asset('assets/images/icon/logoText.png'),
          ),

          /// subhead
          Container(
            width: px(440),
            height: px(66),
            margin: EdgeInsets.only(top: px(40)),
            alignment: Alignment.center,
            decoration: BoxDecoration(
              border: Border(
                top: BorderSide(
                  color: col('cea4dc'),
                  width: px(1),
                ),
                bottom: BorderSide(
                  color: col('cea4dc'),
                  width: px(1),
                ),
              ),
            ),
            child: Text(
              '高颜值视频交友',
              style: TextStyle(
                fontSize: px(26),
                letterSpacing: px(5),
                color: col('eddcf0'),
                height: 1.2,
              ),
            ),
          )
        ],
      ),
    );
  }

  /// bottom
  Widget bottom() {
    return Container(
      margin: EdgeInsets.only(bottom: px(100)),
      child: Column(
        children: <Widget>[
          /// icon
          Container(
            width: px(450),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                _iconBuilder(
                  '手机登录',
                  _phoneLogin,
                  'assets/images/icon/phone.png',
                ),
                _iconBuilder('微信登录', () {}, 'assets/images/icon/wechat.png'),
                _iconBuilder('QQ登录', () {
                  //_tencent?.auth(_login);
                }, 'assets/images/icon/qq.png'),
              ],
            ),
          ),

          /// 服务协议
          _agreement(),
        ],
      ),
    );
  }

  /// Icon构造器
  Widget _iconBuilder(String title, var method, String iconImg) {
    return Container(
      child: Column(
        children: <Widget>[
          /// icon
          Container(
            width: px(80),
            height: px(80),
            child: FlatButton(
              onPressed: method,
              padding: EdgeInsets.zero,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(px(40)))),
              child: Image.asset(iconImg),
            ),
          ),

          /// iconText
          Container(
            margin: EdgeInsets.only(top: px(15)),
            child: Text(
              title,
              style: TextStyle(
                fontSize: px(24),
                color: Colors.white,
                height: 1.2,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 服务协议
  Widget _agreement() {
    return Container(
      margin: EdgeInsets.only(top: px(90)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            "确认登录即代表已阅读并同意",
            style: TextStyle(
              fontSize: px(22),
              color: col("ffffff"),
            ),
          ),
          FlatButton(
            onPressed: () => {},
            padding: EdgeInsets.zero,
            child: Text(
              "《软件服务协议》",
              style: TextStyle(
                fontSize: px(22),
                color: col("ffffff"),
                fontWeight: FontWeight.bold,
              ),
            ),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        bool userChoiceClose = false;
        await TipsDialog.tryCloseApp(
          context,
          () => userChoiceClose = true,
        );
        return Future.value(userChoiceClose);
      },
      child: Scaffold(
        body: Stack(
          children: <Widget>[
            BG(),

            /// 内容
            SafeArea(
              child: Container(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    ///logo
                    logo(),

                    /// bottom
                    bottom(),
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}
